package com.stx.jeepay.payment.service;

import com.stx.jeepay.core.entity.PayOrderEntity;
import com.stx.jeepay.core.entity.RefundOrderEntity;
import com.stx.jeepay.core.service.PayOrderService;
import com.stx.jeepay.core.utils.SpringBeansUtil;
import com.stx.jeepay.payment.channel.IPayOrderQueryService;
import com.stx.jeepay.payment.channel.IRefundService;
import com.stx.jeepay.payment.model.MchAppConfigContext;
import com.stx.jeepay.payment.rqrs.msg.ChannelRetMsg;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Service;

/**
 * 查询上游订单， &  补单服务实现类
 */
@Service
@Slf4j
public class ChannelOrderReissueService {

    @Autowired
    private ConfigContextQueryService configContextQueryService;

    @Autowired
    private PayOrderService payOrderService;

    @Autowired
    private PayOrderProcessService payOrderProcessService;

    @Autowired
    private RefundOrderProcessService refundOrderProcessService;

    @Autowired
    private ApplicationContext applicationContext;

    /**
     * 处理订单
     **/
    public ChannelRetMsg processPayOrder(PayOrderEntity payOrder) {
        try {
            String payOrderId = payOrder.getPayOrderId();

            //查询支付接口是否存在
            IPayOrderQueryService queryService = getBean(payOrder.getIfCode() + "PayOrderQueryService", IPayOrderQueryService.class);

            if (queryService == null) {
                log.error("{} interface not exists!", payOrder.getIfCode());
                return null;
            }

            //查询出商户应用的配置信息
            MchAppConfigContext mchAppConfigContext = configContextQueryService.queryMchInfoAndAppInfo(payOrder.getMchNo(), payOrder.getAppId());

            ChannelRetMsg channelRetMsg = queryService.query(payOrder, mchAppConfigContext);
            if (channelRetMsg == null) {
                log.error("{} interface not exists!", payOrder.getIfCode());
                return null;
            }

            log.info("补单[{}]查询结果为：{}", payOrderId, channelRetMsg);

            // 查询成功
            if (channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_SUCCESS) {
                if (payOrderService.updateIng2Success(payOrderId, channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelUserId())) {
                    //订单支付成功，其他业务逻辑
                    payOrderProcessService.confirmSuccess(payOrder);
                }
            } else if (channelRetMsg.getChannelState() == ChannelRetMsg.ChannelState.CONFIRM_FAIL) {
                //确认失败
                //1. 更新支付订单表为失败状态
                payOrderService.updateIng2Fail(payOrderId, channelRetMsg.getChannelOrderId(), channelRetMsg.getChannelUserId(), channelRetMsg.getChannelErrCode(), channelRetMsg.getChannelErrMsg());
            }

            return channelRetMsg;
        } catch (Exception e) {
            //继续下一次迭代查询
            log.error("error payOrderId = {}", payOrder.getPayOrderId(), e);
            return null;
        }
    }

    public <T> T getBean(String name, Class<T> clazz) {
        if (!applicationContext.containsBean(name)) {
            return null;
        }

        return applicationContext.getBean(name, clazz);
    }

    /**
     * 处理退款订单
     **/
    public ChannelRetMsg processRefundOrder(RefundOrderEntity refundOrder) {
        try {
            String refundOrderId = refundOrder.getRefundOrderId();

            //查询支付接口是否存在
            IRefundService queryService =
                    SpringBeansUtil.getBean(refundOrder.getIfCode() + "RefundService", IRefundService.class);

            // 上游实现不存在
            if (queryService == null) {
                log.error("退款补单：{} interface not exists!", refundOrder.getIfCode());
                return null;
            }

            // 查询商户配置
            MchAppConfigContext mchAppConfigContext =
                    configContextQueryService.queryMchInfoAndAppInfo(refundOrder.getMchNo(), refundOrder.getAppId());

            ChannelRetMsg channelRetMsg = queryService.query(refundOrder, mchAppConfigContext);
            if (channelRetMsg == null) {
                log.error("退款补单：channelRetMsg is null");
                return null;
            }

            log.info("退款补单：[{}]查询结果为：{}", refundOrderId, channelRetMsg);
            // 根据渠道返回结果，处理退款订单
            refundOrderProcessService.handleRefundOrder4Channel(channelRetMsg, refundOrder);

            return channelRetMsg;
        } catch (Exception e) {
            log.error("退款补单：error refundOrderId = {}", refundOrder.getRefundOrderId(), e);
            return null;
        }
    }
}
